<script setup lang="ts">
import type { Product, SearchHistory, HotSearch } from '@/types/mall'
import { formatPrice, debounce } from '@/utils/mall'

const router = useRouter()
const cartStore = useCartStore()

// 接收路由参数
const route = router.currentRoute.value
const initialKeyword = route.query?.keyword as string || ''

// 搜索关键词
const searchKeyword = ref(initialKeyword)

// 搜索结果
const searchResults = ref<Product[]>([])

// 搜索历史
const searchHistory = ref<SearchHistory[]>([
  { id: '1', keyword: 'iPhone', count: 1, createdAt: new Date().toISOString() },
  { id: '2', keyword: 'MacBook', count: 1, createdAt: new Date().toISOString() },
  { id: '3', keyword: '耳机', count: 1, createdAt: new Date().toISOString() },
])

// 热门搜索
const hotSearches = ref<HotSearch[]>([
  { id: '1', keyword: '手机', sort: 1, status: 'active' },
  { id: '2', keyword: '电脑', sort: 2, status: 'active' },
  { id: '3', keyword: '平板', sort: 3, status: 'active' },
  { id: '4', keyword: '耳机', sort: 4, status: 'active' },
  { id: '5', keyword: '智能手表', sort: 5, status: 'active' },
  { id: '6', keyword: '充电器', sort: 6, status: 'active' },
  { id: '7', keyword: '数据线', sort: 7, status: 'active' },
  { id: '8', keyword: '保护壳', sort: 8, status: 'active' },
])

// 搜索状态
const searching = ref(false)
const hasSearched = ref(false)

// 排序选项
const sortOptions = [
  { label: '综合排序', value: 'default' },
  { label: '价格从低到高', value: 'price_asc' },
  { label: '价格从高到低', value: 'price_desc' },
  { label: '销量从高到低', value: 'sales_desc' },
]

const currentSort = ref('default')
const showSortSheet = ref(false)

// 模拟搜索结果数据
const mockProducts: Product[] = [
  {
    id: '1',
    name: 'iPhone 15 Pro Max',
    description: '全新iPhone 15 Pro Max，搭载A17 Pro芯片',
    categoryId: '1',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg'],
    defaultPrice: 999900,
    originalPrice: 1099900,
    sales: 1200,
    stock: 50,
    status: 'active',
    rating: 4.8,
    reviewCount: 520,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '2',
    name: 'MacBook Air M3',
    description: '搭载M3芯片的MacBook Air，性能卓越',
    categoryId: '2',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/macbook-air-13-m3-midnight-pdp-image-position-1_CN.jpg'],
    defaultPrice: 899900,
    originalPrice: 999900,
    sales: 800,
    stock: 30,
    status: 'active',
    rating: 4.9,
    reviewCount: 350,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
]

// 执行搜索
const performSearch = debounce(async (keyword: string) => {
  if (!keyword.trim()) {
    searchResults.value = []
    hasSearched.value = false
    return
  }

  searching.value = true
  hasSearched.value = true

  try {
    // TODO: 调用搜索API
    // const response = await api.product.searchProducts({ keyword })
    // searchResults.value = response.data.list

    // 模拟搜索结果
    await new Promise(resolve => setTimeout(resolve, 800))
    searchResults.value = mockProducts.filter(product => 
      product.name.toLowerCase().includes(keyword.toLowerCase()) ||
      product.description.toLowerCase().includes(keyword.toLowerCase())
    )

    // 保存搜索历史
    saveSearchHistory(keyword)
  } catch (error) {
    console.error('搜索失败:', error)
    uni.showToast({ title: '搜索失败', icon: 'none' })
  } finally {
    searching.value = false
  }
}, 500)

// 搜索输入处理
function onSearchInput(event: any) {
  const keyword = event.detail.value
  searchKeyword.value = keyword
  performSearch(keyword)
}

// 执行搜索（点击搜索按钮）
function handleSearch() {
  if (!searchKeyword.value.trim()) {
    uni.showToast({ title: '请输入搜索关键词', icon: 'none' })
    return
  }
  performSearch(searchKeyword.value.trim())
}

// 点击热门搜索
function clickHotSearch(keyword: string) {
  searchKeyword.value = keyword
  performSearch(keyword)
}

// 点击搜索历史
function clickSearchHistory(keyword: string) {
  searchKeyword.value = keyword
  performSearch(keyword)
}

// 保存搜索历史
function saveSearchHistory(keyword: string) {
  const existingIndex = searchHistory.value.findIndex(item => item.keyword === keyword)
  
  if (existingIndex >= 0) {
    // 更新已存在的搜索记录
    const item = searchHistory.value[existingIndex]
    item.count++
    item.createdAt = new Date().toISOString()
    // 移到最前面
    searchHistory.value.splice(existingIndex, 1)
    searchHistory.value.unshift(item)
  } else {
    // 添加新的搜索记录
    const newHistory: SearchHistory = {
      id: Date.now().toString(),
      keyword,
      count: 1,
      createdAt: new Date().toISOString(),
    }
    searchHistory.value.unshift(newHistory)
    
    // 最多保留10条搜索历史
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
  }
  
  // TODO: 保存到本地存储或服务器
}

// 清空搜索历史
function clearSearchHistory() {
  uni.showModal({
    title: '清空搜索历史',
    content: '确定要清空搜索历史吗？',
    success: (res) => {
      if (res.confirm) {
        searchHistory.value = []
        uni.showToast({ title: '已清空', icon: 'success' })
      }
    }
  })
}

// 删除单条搜索历史
function deleteSearchHistory(index: number) {
  searchHistory.value.splice(index, 1)
}

// 跳转到商品详情
function goToProductDetail(productId: string) {
  uni.navigateTo({ url: `/subPackages/product-package/goodsDetail/index?id=${productId}` })
}

// 添加到购物车
async function addToCart(product: Product) {
  try {
    const success = await (cartStore as any).addToCart(product)
    if (success) {
      uni.vibrateShort()
    }
  } catch (error) {
    console.error('添加到购物车失败:', error)
    uni.showToast({ title: '添加到购物车失败', icon: 'none' })
  }
}

// 显示排序选择
function showSortOptions() {
  showSortSheet.value = true
}

// 选择排序方式
function selectSort(sortValue: string) {
  currentSort.value = sortValue
  showSortSheet.value = false
  
  // TODO: 根据排序重新搜索
  if (hasSearched.value) {
    performSearch(searchKeyword.value)
  }
}

// 页面生命周期
onMounted(() => {
  if (initialKeyword) {
    performSearch(initialKeyword)
  }
})
</script>

<template>
  <view class="search-page">
    <!-- 搜索栏 -->
    <view class="search-header">
      <view class="search-input-wrapper">
        <wd-icon name="search" size="16px" color="#999" />
        <input
          v-model="searchKeyword"
          class="search-input"
          placeholder="搜索商品"
          focus
          @input="onSearchInput"
          @confirm="handleSearch"
        />
        <view v-if="searchKeyword" class="clear-btn" @click="searchKeyword = ''">
          <wd-icon name="close-bold" size="14px" color="#999" />
        </view>
      </view>
      
      <view class="search-btn" @click="handleSearch">
        搜索
      </view>
    </view>

    <!-- 搜索内容区域 -->
    <view class="search-content">
      <!-- 搜索结果 -->
      <view v-if="hasSearched" class="search-results">
        <!-- 排序栏 -->
        <view v-if="searchResults.length > 0" class="sort-bar">
          <text class="result-count">共{{ searchResults.length }}个结果</text>
          <view class="sort-btn" @click="showSortOptions">
            <text>{{ sortOptions.find(s => s.value === currentSort)?.label }}</text>
            <wd-icon name="arrow-down" size="12px" color="#999" />
          </view>
        </view>

        <!-- 搜索中 -->
        <view v-if="searching" class="searching">
          <wd-loading size="20px" />
          <text>搜索中...</text>
        </view>

        <!-- 无搜索结果 -->
        <view v-else-if="searchResults.length === 0" class="no-results">
          <wd-icon name="search" size="60px" color="#ddd" />
          <text class="no-results-text">没有找到相关商品</text>
          <text class="no-results-desc">试试其他关键词吧</text>
        </view>

        <!-- 商品列表 -->
        <view v-else class="product-list">
          <view
            v-for="product in searchResults"
            :key="product.id"
            class="product-item"
            @click="goToProductDetail(product.id)"
          >
            <image :src="product.images[0]" class="product-image" mode="aspectFit" />
            
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <text class="product-desc">{{ product.description }}</text>
              
              <view class="product-price">
                <text class="current-price">{{ formatPrice(product.defaultPrice) }}</text>
                <text v-if="product.originalPrice && product.originalPrice > product.defaultPrice" class="original-price">
                  {{ formatPrice(product.originalPrice) }}
                </text>
              </view>
              
              <view class="product-stats">
                <view class="rating">
                  <wd-icon name="star-on" size="12px" color="#ffc107" />
                  <text>{{ product.rating }}</text>
                </view>
                <text class="sales">已售{{ product.sales }}+</text>
              </view>
            </view>
            
            <view class="add-cart-btn" @click.stop="addToCart(product)">
              <wd-icon name="cart" size="16px" color="#fff" />
            </view>
          </view>
        </view>
      </view>

      <!-- 搜索建议 -->
      <view v-else class="search-suggestions">
        <!-- 搜索历史 -->
        <view v-if="searchHistory.length > 0" class="history-section">
          <view class="section-header">
            <text class="section-title">搜索历史</text>
            <view class="clear-history" @click="clearSearchHistory">
              <wd-icon name="delete" size="14px" color="#999" />
            </view>
          </view>
          
          <view class="history-list">
            <view
              v-for="(item, index) in searchHistory"
              :key="item.id"
              class="history-item"
              @click="clickSearchHistory(item.keyword)"
            >
              <wd-icon name="time" size="14px" color="#999" />
              <text class="history-keyword">{{ item.keyword }}</text>
              <view class="delete-history" @click.stop="deleteSearchHistory(index)">
                <wd-icon name="close" size="12px" color="#ccc" />
              </view>
            </view>
          </view>
        </view>

        <!-- 热门搜索 -->
        <view class="hot-section">
          <view class="section-header">
            <text class="section-title">热门搜索</text>
          </view>
          
          <view class="hot-tags">
            <view
              v-for="item in hotSearches"
              :key="item.id"
              class="hot-tag"
              @click="clickHotSearch(item.keyword)"
            >
              {{ item.keyword }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 排序选择弹窗 -->
    <wd-action-sheet
      v-model="showSortSheet"
      title="选择排序方式"
      :close-on-click-action="true"
    >
      <view class="sort-options">
        <view
          v-for="option in sortOptions"
          :key="option.value"
          class="sort-option"
          :class="{ active: currentSort === option.value }"
          @click="selectSort(option.value)"
        >
          <text>{{ option.label }}</text>
          <wd-icon
            v-if="currentSort === option.value"
            name="check"
            size="16px"
            color="var(--wot-color-theme)"
          />
        </view>
      </view>
    </wd-action-sheet>
  </view>
</template>

<style lang="scss" scoped>
.search-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background: white;
  gap: 10px;

  .search-input-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    background: #f5f5f5;
    border-radius: 20px;
    padding: 8px 15px;
    gap: 8px;

    .search-input {
      flex: 1;
      border: none;
      outline: none;
      background: transparent;
      font-size: 14px;
      color: #333;
    }

    .clear-btn {
      padding: 2px;
    }
  }

  .search-btn {
    padding: 8px 16px;
    background: var(--wot-color-theme);
    color: white;
    border-radius: 16px;
    font-size: 14px;
  }
}

.search-content {
  flex: 1;
}

.search-results {
  .sort-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background: white;
    margin-bottom: 10px;

    .result-count {
      font-size: 12px;
      color: #666;
    }

    .sort-btn {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 6px 12px;
      background: #f5f5f5;
      border-radius: 16px;
      font-size: 12px;
      color: #666;
    }
  }

  .searching {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 20px;
    gap: 15px;
    font-size: 14px;
    color: #666;
  }

  .no-results {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 20px;

    .no-results-text {
      margin: 15px 0 8px;
      font-size: 16px;
      color: #333;
    }

    .no-results-desc {
      font-size: 14px;
      color: #999;
    }
  }

  .product-list {
    padding: 0 15px;

    .product-item {
      position: relative;
      display: flex;
      background: white;
      border-radius: 8px;
      margin-bottom: 10px;
      padding: 15px;

      .product-image {
        width: 90px;
        height: 90px;
        border-radius: 6px;
        margin-right: 12px;
        background: #f8f9fa;
      }

      .product-info {
        flex: 1;

        .product-name {
          font-size: 14px;
          font-weight: bold;
          color: #333;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          margin-bottom: 4px;
        }

        .product-desc {
          font-size: 12px;
          color: #666;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
          margin-bottom: 8px;
        }

        .product-price {
          display: flex;
          align-items: center;
          gap: 6px;
          margin-bottom: 6px;

          .current-price {
            font-size: 16px;
            font-weight: bold;
            color: #ff4142;
          }

          .original-price {
            font-size: 12px;
            color: #999;
            text-decoration: line-through;
          }
        }

        .product-stats {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .rating {
            display: flex;
            align-items: center;
            gap: 2px;
            font-size: 11px;
            color: #666;
          }

          .sales {
            font-size: 11px;
            color: #999;
          }
        }
      }

      .add-cart-btn {
        position: absolute;
        bottom: 15px;
        right: 15px;
        width: 32px;
        height: 32px;
        background: var(--wot-color-theme);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.search-suggestions {
  padding: 15px;

  .history-section,
  .hot-section {
    background: white;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .section-title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
      }

      .clear-history {
        padding: 4px;
      }
    }
  }

  .history-list {
    .history-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 10px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .history-keyword {
        flex: 1;
        font-size: 14px;
        color: #333;
      }

      .delete-history {
        padding: 4px;
      }
    }
  }

  .hot-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .hot-tag {
      padding: 6px 12px;
      background: #f5f5f5;
      border-radius: 16px;
      font-size: 12px;
      color: #666;
    }
  }
}

.sort-options {
  padding: 20px;

  .sort-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    &.active {
      color: var(--wot-color-theme);
    }
  }
}
</style>

<route lang="json">
{
  "name": "search",
  "style": {
    "navigationBarTitleText": "搜索"
  }
}
</route>